﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base;
using UFIDA.U9.Base.UserRole;
using UFIDA.U9.Cust.YYD.PlugBE.Dtos;
using UFIDA.U9.Cust.YYD.PlugBE.Public;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.Cust.YYD.PlugBE.PRP
{
    public class AfterUpdating : UFSoft.UBF.Eventing.IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            var holder = key.GetEntity() as UFIDA.U9.PR.PurchaseRequest.PR;
            if (holder == null)
                return;
            #endregion

            //提交传
            if (holder.OriginalData.Status == PR.PurchaseRequest.PRStatusEnum.OpenOpen && holder.Status == PR.PurchaseRequest.PRStatusEnum.Approving)
            {

                string workflowId = string.Empty;
                string formId = string.Empty;
                string subFormId = string.Empty;
                switch (holder.PRDocType.Code)
                {
                    case "PR01"://研发工程请购
                        workflowId = "1203294839804739584";
                        formId = "1203291631422226436";
                        subFormId = "1203291631422226508";
                        break;
                    case "PR02"://MRP采购请购
                        workflowId = "1203295050165862401";
                        formId = "1203291893448785922";
                        subFormId = "1203291893448785994";
                        break;
                    case "PR03"://生产请购
                        workflowId = "1203295385030705153";
                        formId = "1203292013548486656";
                        subFormId = "1203292013548486728";
                        break;
                    case "PR04"://部门请购
                        workflowId = "1203296381572169734";
                        formId = "1203292116594147328";
                        subFormId = "1203292116594147400";
                        break;
                    case "PR05"://模具资产请购
                        workflowId = "1203296527735275524";
                        formId = "1203292245585772545";
                        subFormId = "1203292245585772617";
                        break;
                    case "YZPRout01"://委外请购
                        workflowId = "1203296776692383745";
                        formId = "1203292473084821505";
                        subFormId = "1203292473084821577";
                        break;
                    case "PR07"://固定资产请购
                        workflowId = "1203301101799948296";
                        formId = "1203292357263310850";
                        subFormId = "1203292357263310922";
                        break;

                }

                if (string.IsNullOrEmpty(workflowId))
                {
                    return;
                }

                //新增
                if (string.IsNullOrEmpty(holder.DescFlexField.PrivateDescSeg1))
                {
                    HttpHelper httpHelper = new HttpHelper();
                    var token = httpHelper.GetOAToken();
                    JsonConfig config = new JsonConfig();
                    httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/api/workflow/core/paService/v1/doCreateRequest";

                    User user = User.Finder.FindByID(Context.LoginUserID);
                    var userinfo = httpHelper.GetOAUserInfo(token, user.Code);




                    OADTO dto = new OADTO();
                    dto.access_token = token;
                    dto.userid = userinfo.Key;
                    dto.workflowId = workflowId;
                    var formData = new FormData();
                    formData.formId = formId;
                    var dataDetails = new List<DataDetailsItem>();



                    //申请人
                    DataDetailsItem d1 = new DataDetailsItem();
                    d1.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = Context.LoginUser,
                        optionId = userinfo.Key,
                        type ="resource"
                    }};
                    d1.dataKey = "sqr";
                    dataDetails.Add(d1);

                    //申请部门
                    DataDetailsItem d2 = new DataDetailsItem();
                    d2.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content="",
                        optionId= userinfo.Value,
                        type="department"
                    }};
                    d2.dataKey = "sqbm";
                    dataDetails.Add(d2);

                    //推送日期
                    DataDetailsItem d3 = new DataDetailsItem();
                    d3.content = DateTime.Now.Date.ToShortDateString();
                    d3.dataKey = "tsrq";
                    dataDetails.Add(d3);

                    //单据类型
                    DataDetailsItem d4 = new DataDetailsItem();
                    d4.content = holder.PRDocType.Name;
                    d4.dataKey = "djlx";
                    dataDetails.Add(d4);

                    //来源类别
                    string sql = $@" select dbo.F_GetEnumName('UFIDA.U9.PR.PurchaseRequest.SrcDocTypeEnum','{holder.SourceType.Value}','zh-CN') SrcDocType";
                    DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out DataSet ds);
                    string SrcDocType = ds.Tables[0].Rows[0]["SrcDocType"].ToString();
                    DataDetailsItem d5 = new DataDetailsItem();
                    d5.content = SrcDocType;
                    d5.dataKey = "lylb";
                    dataDetails.Add(d5);

                    //单据日期
                    DataDetailsItem d6 = new DataDetailsItem();
                    d6.content = holder.BusinessDate.ToShortDateString();
                    d6.dataKey = "djrq";
                    dataDetails.Add(d6);

                    //核算组织
                    DataDetailsItem d7 = new DataDetailsItem();
                    d7.content = holder.AccountOrg.Name;
                    d7.dataKey = "hszz";
                    dataDetails.Add(d7);


                    //流程编号
                    DataDetailsItem d8 = new DataDetailsItem();
                    d8.content = holder.DocNo;
                    d8.dataKey = "lcbh";
                    dataDetails.Add(d8);

                    foreach (var line in holder.PRLineList)
                    {
                        //需求分类
                        string sql1 = $@" select dbo.F_GetEnumName('UFIDA.U9.CBO.Enums.DemandCodeEnum','{line.DemandCode.Value}','zh-CN') DemandCodeName";
                        DataAccessor.RunSQL(DataAccessor.GetConn(), sql1, null, out DataSet ds1);
                        string DemandCodeName = ds1.Tables[0].Rows[0]["DemandCodeName"].ToString();
                        DataDetailsItem it1 = new DataDetailsItem();
                        it1.content = DemandCodeName;
                        it1.dataIndex = line.DocLineNo / 10;
                        it1.dataKey = "xqfl";
                        it1.subFormId = subFormId;
                        dataDetails.Add(it1);

                        //项目
                        DataDetailsItem it2 = new DataDetailsItem();
                        it2.content = line.Project.Name;
                        it2.dataIndex = line.DocLineNo / 10;
                        it2.dataKey = "xm";
                        it2.subFormId = subFormId;
                        dataDetails.Add(it2);

                        //料号
                        DataDetailsItem it3 = new DataDetailsItem();
                        it3.content = line.ItemInfo.ItemID.Code;
                        it3.dataIndex = line.DocLineNo / 10;
                        it3.dataKey = "lh";
                        it3.subFormId = subFormId;
                        dataDetails.Add(it3);

                        //参考料号
                        DataDetailsItem it4 = new DataDetailsItem();
                        it4.content = line.ItemInfo.ItemID.Code1;
                        it4.dataIndex = line.DocLineNo / 10;
                        it4.dataKey = "pm";
                        it4.subFormId = subFormId;
                        dataDetails.Add(it4);

                        //品名
                        DataDetailsItem it5 = new DataDetailsItem();
                        it5.content = line.ItemInfo.ItemID.Name;
                        it5.dataIndex = line.DocLineNo / 10;
                        it5.dataKey = "pm";
                        it5.subFormId = subFormId;
                        dataDetails.Add(it5);


                        //交易单位
                        DataDetailsItem it6 = new DataDetailsItem();
                        it6.content = line.TradeUOM.Name;
                        it6.dataIndex = line.DocLineNo / 10;
                        it6.dataKey = "jydw";
                        it6.subFormId = subFormId;
                        dataDetails.Add(it6);


                        //需求数量
                        DataDetailsItem it7 = new DataDetailsItem();
                        it7.content = line.ReqQtyTU.ToString();
                        it7.dataIndex = line.DocLineNo / 10;
                        it7.dataKey = "xqsl";
                        it7.subFormId = subFormId;
                        dataDetails.Add(it7);

                        //核准数量
                        DataDetailsItem it8 = new DataDetailsItem();
                        it8.content = line.ApprovedQtyTU.ToString();
                        it8.dataIndex = line.DocLineNo / 10;
                        it8.dataKey = "hzsl";
                        it8.subFormId = subFormId;
                        dataDetails.Add(it8);

                        //计价单位
                        DataDetailsItem it9 = new DataDetailsItem();
                        it9.content = line.PriceUOM.Name;
                        it9.dataIndex = line.DocLineNo / 10;
                        it9.dataKey = "jjdw";
                        it9.subFormId = subFormId;
                        dataDetails.Add(it9);

                        //要求交货日期
                        DataDetailsItem it10 = new DataDetailsItem();
                        it10.content = line.RequiredDeliveryDate.ToShortDateString();
                        it10.dataIndex = line.DocLineNo / 10;
                        it10.dataKey = "yqjhrq";
                        it10.subFormId = subFormId;
                        dataDetails.Add(it10);

                        //收费组织
                        DataDetailsItem it11 = new DataDetailsItem();
                        it11.content = line.RcvOrg.Name;
                        it11.dataIndex = line.DocLineNo / 10;
                        it11.dataKey = "sfzz";
                        it11.subFormId = subFormId;
                        dataDetails.Add(it11);

                        
                    }

                    formData.dataDetails = dataDetails;
                    dto.formData = formData;
                    dto.otherParams = new OtherParams { isnextflow = "1" };
                    httpHelper.Content = JsonConvert.SerializeObject(dto);
                    var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                    if (result["message"]["errmsg"].ToString() != "success")
                    {
                        throw new Exception(result["message"]["errmsg"].ToString());
                    }

                    holder.DescFlexField.PrivateDescSeg1 = result["message"]["requestId"].ToString();
                }
                else
                {
                    HttpHelper httpHelper = new HttpHelper();
                    var token = httpHelper.GetOAToken();
                    JsonConfig config = new JsonConfig();
                    httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/api/workflow/core/paService/v1/submitRequest";

                    User user = User.Finder.FindByID(Context.LoginUserID);
                    var userinfo = httpHelper.GetOAUserInfo(token, user.Code);

                    OAUpdateDTO dto = new OAUpdateDTO();
                    dto.access_token = token;
                    dto.userid = userinfo.Key;
                    dto.requestId = holder.DescFlexField.PrivateDescSeg1;
                    var formData = new FormData();
                    formData.formId = formId;
                    var dataDetails = new List<DataDetailsItem>();



                    //申请人
                    DataDetailsItem d1 = new DataDetailsItem();
                    d1.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = Context.LoginUser,
                        optionId = userinfo.Key,
                        type ="resource"
                    }};
                    d1.dataKey = "sqr";
                    dataDetails.Add(d1);

                    //申请部门
                    DataDetailsItem d2 = new DataDetailsItem();
                    d2.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content="",
                        optionId= userinfo.Value,
                        type="department"
                    }};
                    d2.dataKey = "sqbm";
                    dataDetails.Add(d2);

                    //推送日期
                    DataDetailsItem d3 = new DataDetailsItem();
                    d3.content = DateTime.Now.Date.ToShortDateString();
                    d3.dataKey = "tsrq";
                    dataDetails.Add(d3);

                    //单据类型
                    DataDetailsItem d4 = new DataDetailsItem();
                    d4.content = holder.PRDocType.Name;
                    d4.dataKey = "djlx";
                    dataDetails.Add(d4);

                    //来源类别
                    string sql = $@" select dbo.F_GetEnumName('UFIDA.U9.PR.PurchaseRequest.SrcDocTypeEnum','{holder.SourceType.Value}','zh-CN') SrcDocType";
                    DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out DataSet ds);
                    string SrcDocType = ds.Tables[0].Rows[0]["SrcDocType"].ToString();
                    DataDetailsItem d5 = new DataDetailsItem();
                    d5.content = SrcDocType;
                    d5.dataKey = "lylb";
                    dataDetails.Add(d5);

                    //单据日期
                    DataDetailsItem d6 = new DataDetailsItem();
                    d6.content = holder.BusinessDate.ToShortDateString();
                    d6.dataKey = "djrq";
                    dataDetails.Add(d6);

                    //核算组织
                    DataDetailsItem d7 = new DataDetailsItem();
                    d7.content = holder.AccountOrg.Name;
                    d7.dataKey = "hszz";
                    dataDetails.Add(d7);


                    //流程编号
                    DataDetailsItem d8 = new DataDetailsItem();
                    d8.content = holder.DocNo;
                    d8.dataKey = "lcbh";
                    dataDetails.Add(d8);

                    foreach (var line in holder.PRLineList)
                    {
                        //需求分类
                        string sql1 = $@" select dbo.F_GetEnumName('UFIDA.U9.CBO.Enums.DemandCodeEnum','{line.DemandCode.Value}','zh-CN') DemandCodeName";
                        DataAccessor.RunSQL(DataAccessor.GetConn(), sql1, null, out DataSet ds1);
                        string DemandCodeName = ds1.Tables[0].Rows[0]["DemandCodeName"].ToString();
                        DataDetailsItem it1 = new DataDetailsItem();
                        it1.content = DemandCodeName;
                        it1.dataIndex = line.DocLineNo / 10;
                        it1.dataKey = "xqfl";
                        it1.subFormId = subFormId;
                        dataDetails.Add(it1);

                        //项目
                        DataDetailsItem it2 = new DataDetailsItem();
                        it2.content = line.Project.Name;
                        it2.dataIndex = line.DocLineNo / 10;
                        it2.dataKey = "xm";
                        it2.subFormId = subFormId;
                        dataDetails.Add(it2);

                        //料号
                        DataDetailsItem it3 = new DataDetailsItem();
                        it3.content = line.ItemInfo.ItemID.Code;
                        it3.dataIndex = line.DocLineNo / 10;
                        it3.dataKey = "lh";
                        it3.subFormId = subFormId;
                        dataDetails.Add(it3);

                        //参考料号
                        DataDetailsItem it4 = new DataDetailsItem();
                        it4.content = line.ItemInfo.ItemID.Code1;
                        it4.dataIndex = line.DocLineNo / 10;
                        it4.dataKey = "pm";
                        it4.subFormId = subFormId;
                        dataDetails.Add(it4);

                        //品名
                        DataDetailsItem it5 = new DataDetailsItem();
                        it5.content = line.ItemInfo.ItemID.Name;
                        it5.dataIndex = line.DocLineNo / 10;
                        it5.dataKey = "pm";
                        it5.subFormId = subFormId;
                        dataDetails.Add(it5);


                        //交易单位
                        DataDetailsItem it6 = new DataDetailsItem();
                        it6.content = line.TradeUOM.Name;
                        it6.dataIndex = line.DocLineNo / 10;
                        it6.dataKey = "jydw";
                        it6.subFormId = subFormId;
                        dataDetails.Add(it6);


                        //需求数量
                        DataDetailsItem it7 = new DataDetailsItem();
                        it7.content = line.ReqQtyTU.ToString();
                        it7.dataIndex = line.DocLineNo / 10;
                        it7.dataKey = "xqsl";
                        it7.subFormId = subFormId;
                        dataDetails.Add(it7);

                        //核准数量
                        DataDetailsItem it8 = new DataDetailsItem();
                        it8.content = line.ApprovedQtyTU.ToString();
                        it8.dataIndex = line.DocLineNo / 10;
                        it8.dataKey = "hzsl";
                        it8.subFormId = subFormId;
                        dataDetails.Add(it8);

                        //计价单位
                        DataDetailsItem it9 = new DataDetailsItem();
                        it9.content = line.PriceUOM.Name;
                        it9.dataIndex = line.DocLineNo / 10;
                        it9.dataKey = "jjdw";
                        it9.subFormId = subFormId;
                        dataDetails.Add(it9);

                        //要求交货日期
                        DataDetailsItem it10 = new DataDetailsItem();
                        it10.content = line.RequiredDeliveryDate.ToShortDateString();
                        it10.dataIndex = line.DocLineNo / 10;
                        it10.dataKey = "yqjhrq";
                        it10.subFormId = subFormId;
                        dataDetails.Add(it10);

                        //收费组织
                        DataDetailsItem it11 = new DataDetailsItem();
                        it11.content = line.RcvOrg.Name;
                        it11.dataIndex = line.DocLineNo / 10;
                        it11.dataKey = "sfzz";
                        it11.subFormId = subFormId;
                        dataDetails.Add(it11);


                    }

                    formData.dataDetails = dataDetails;
                    dto.formData = formData;
                    var Content = JsonConvert.SerializeObject(dto);
                    httpHelper.Content = Content.Remove(Content.Length - 2, 2) + $@" }},""seniorFormParam"": {{""subFormMatchFields"": {{ ""{subFormId}"": {{""cover"": true,""subFormMatchMore"": ""ZERO"",""subFormNoMatch"": ""ADD""}}}}}}, ""isNewFormData"": true}}";
                    var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                    if (result["message"]["errmsg"].ToString() != "success")
                    {
                        throw new Exception(result["message"]["errmsg"].ToString());
                    }
                }
              
            }
        }
    }
}
